<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="../lib/sugar.html">
<script src="../scripts/results.js"></script>

<link rel="import" href="../bower_components/app-router/app-router.html">
<link rel="import" href="../bower_components/core-animated-pages/core-animated-pages.html">
<link rel="import" href="../bower_components/core-animated-pages/transitions/slide-from-right.html">
<link rel="import" href="../lib/analytics.html">
<link rel="import" href="../lib/ct-scheduled-updater.html">
<link rel="import" href="../model/ct-repositories.html">
<link rel="import" href="../model/ct-rotations.html">
<link rel="import" href="../model/ct-failures.html">
<link rel="import" href="../model/ct-tree-list.html">
<link rel="import" href="ct-health.html">
<link rel="import" href="ct-party-time.html">
<link rel="import" href="ct-results-panel.html">
<link rel="import" href="ct-tree-select.html">
<link rel="import" href="ct-banner.html">
<link rel="import" href="ct-trooper-card.html">
<link rel="import" href="ct-unexpected-failures.html">

<link rel="import" href="../bower_components/core-scaffold/core-scaffold.html">
<link rel="import" href="../bower_components/core-header-panel/core-header-panel.html">
<link rel="import" href="../bower_components/core-menu/core-menu.html">
<link rel="import" href="../bower_components/core-pages/core-pages.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/paper-spinner/paper-spinner.html">
<link rel="import" href="../bower_components/core-icon-button/core-icon-button.html">
<link rel="import" href="../bower_components/core-toolbar/core-toolbar.html">
<link rel="import" href="../bower_components/core-menu/core-submenu.html">
<link rel="import" href="../bower_components/core-icons/maps-icons.html">

<polymer-element name="ct-sheriff-o-matic" attributes="tree">
  <template>
    <style>
      :host {
        display: flex;
        flex-direction: column;
        height: 100%;
      }
      header {
        -webkit-user-select: none;
        align-items: center;
        background-color: #212121;
        color: white;
        cursor: default;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        font-size: 1.1em;
        padding: 0 5px;
        white-space: nowrap;
      }
      header span {
        color: white;
        display: inline-block;
        padding: 0.25em 4px;
        text-decoration: none;
      }
      #right-toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
      }
      ct-last-updated {
        margin: 0 5px;
      }
      core-animated-pages {
        flex: 1;
      }
      core-animated-pages > * {
        overflow: auto;
      }
      :host {
        position: absolute;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
      }

      core-scaffold::shadow core-toolbar {
        color: #E5E5E5;
        background: black;
      }

      core-scaffold::shadow core-header-panel::shadow core-toolbar {
        background: #FFF;
        color: black;
      }

      #core_header_panel {
        background-color: rgb(255, 255, 255);
      }

      #main_toolbar {
        background: #666;
      }

      #main_menu {
        font-size: 16px;
      }

      #main_pages {
        height: 100%;
      }

      div[tool] {
        width:100%;
      }

      app-router,
      active-route,
      app-route[active="active"] {
        display: block;
      }

      app-route {
        display: none;
      }

      #main_menu paper-item {
        padding-left: 24px;
      }

      #main_menu core-item {
        font-weight: bold;
      }
      #historyLink {
        color: white;
      }
      #historyLinkButton {
        padding: 0;
      }
    </style>
    <core-scaffold id="main_scaffold" responsiveWidth="1200px">
      <core-header-panel mode="seamed" id="core_header_panel" navigation flex>
        <core-toolbar id="main_toolbar"></core-toolbar>
        <div valueattr="id" id="main_menu">
          <core-menu id="menu" valueattr="id" on-core-select="{{ menuSelected }}">
            <core-item icon="folder" label="Trees" notap="true"></core-item>
            <template repeat="{{ t in treeList.trees }}">
              <paper-item id="{{ t.name }}" label="{{ t.displayName }}" horizontal center layout>
                {{ t.displayName }}
              </paper-item>
            </template>

            <core-item icon="help" label="Help" notap="true"></core-item>

            <paper-item id="help_links" label="Useful Links" horizontal center layout>Useful Links</paper-item>
            <paper-item id="help_calendar" label="Rotation Calendar" horizontal center layout>Rotation Calendar</paper-item>
            <paper-item id="health" label="System Health" horizontal center layout>System Health</paper-item>
          </core-menu>
          <div flex vertical layout center>
            <paper-button id="feedback_button" on-click="{{ fileSoMBug }}" raised="" role="button">
              <core-icon icon="bug-report" aria-label="bug-report" role="img"></core-icon>&nbsp;File a Bug
            </paper-button>
          </div>
        </div>
      </core-header-panel>

      <div tool layout vertical>
        <div horizontal layout>
          <div flex>Sheriff-O-Matic: {{ page_title }}</div>
            <paper-spinner id="spinner" active="true"></paper-spinner>
            <a id="historyLink" href="{{tree}}?history={{ alertsHistoryKey }}"><paper-icon-button id="historyLinkButton" icon="link" title="permalink to this set of alerts" hidden?="{{ !alertsHistoryKey }}"></paper-icon-button></a>
          <ct-last-updated date="{{ failures.lastUpdateDate }}"></ct-last-updated>
        </div>
        <ct-banner id="trooperBanner"></ct-banner>
      </div>
      <div layout vertical>

        <!-- main content area -->
        <div fit>

          <app-router id="router" trailingSlash="ignore" fit mode="pushstate">
            <app-route path="/help_links" fit>
              <template>
                <h1>Helpful Links</h1>
                <ul>
                  <li><a href="https://code.google.com/p/chromium/wiki/UsefulURLs">Useful URLs</a></li>
                  <li><a href="http://www.chromium.org/developers/tree-sheriffs/sheriff-details-chromium">How to Sheriff</a></li>
                  <li><a href="https://sites.google.com/a/chromium.org/dev/developers/testing/contacting-a-trooper">How to contact a Trooper</a></li>
                </ul>
              </template>
            </app-route>

            <app-route path="/help_calendar" fit>
              <template>
                <iframe fit src="https://chromium-build.appspot.com/static/rotations.html" width="100%" height="100%"></iframe>
              </template>
            </app-route>

            <app-route path="/health" fit on-before-data-binding="{{ bindHealth }}">
              <template>
                <ct-health failures="{{ failures }}"></ct-health>
              </template>
            </app-route>

            <app-route path="/:tree" fit on-before-data-binding="{{ modifyTreeModel }}">
              <template>
                <ct-unexpected-failures id="unexpected" tree="{{ tree }}" repositories="{{ repositories }}" failures="{{ failures }}"></ct-unexpected-failures>
              </template>
            </app-route>

            <app-route path="/:tree/failure/:failureGroupKey" fit on-before-data-binding="{{ modifyFailureGroupModel }}">
              <template>
              <ct-results-panel fit id="resultsPanel" group="{{ examinedFailureGroup }}" failureGroupKey="{{ failureGroupKey }}" tree="{{ tree || 'chromium' }}"></ct-results-panel>
              </template>
            </app-route>

            <app-route path="/" redirect="/chromium"></app-route>

          </app-router>
        </div>
      </div>
    </core-scaffold>
  </template>
  <script>
    var kUpdateFrequency = 1000 * 30;

    Polymer({
      page_title: "Chromium",
      tree: '',
      treeList: null,
      examinedFailureGroup: null,
      alertsHistoryKey: null,
      _pendingFailureGroupKey: '',

      menuSelected: function(e, detail, sender) {
        if (!e.detail.isSelected) {
          return;
        }
        var pageId = e.detail.item.id;
        if (!pageId) {
          return;
        }

        this.tree = pageId;
        this.page_title = e.detail.item.innerText;
        this.$.main_scaffold.closeDrawer();
        history.pushState(null, null, pageId + window.location.search);
        this.$.router.go();
      },
      bindHealth: function(e) {
        e.detail.model.failures = this.failures;
      },

      modifyTreeModel: function(e) {
        e.detail.model.repositories = this.repositories;
        e.detail.model.failures = this.failures;
      },

      modifyFailureGroupModel: function(e) {
        e.detail.model.examinedFailureGroup = this.examinedFailureGroup;
        this._pendingFailureGroupKey = e.detail.model.failureGroupKey;
        this.failureGroupKey = e.detail.model.failureGroupKey;
      },

      attached: function() {
        var pathParts = window.location.pathname.split('/');
        this.tree = pathParts[1];
        // This can be called before $ exists.
        // It can also be called for /:tree/examine links, which in
        // this case would trigger a navigation to /:tree when we
        // try to highlight the current tree in the submenu, so
        // we don't highlight anything on the nav menu in that case.
        if (pathParts.length == 2 && this.$) {
          this.$.menu.items.forEach(function(item) {
            if (item.id == this.tree) {
              this.$.menu.selected = this.tree;
            }
          }, this);
        }
      },

      created: function() {
        this.treeList = new CTTreeList();
        this._defaultPath = '/' + this.treeList.defaultValue();
        this.repositories  = new CTRepositories();
        this.failures = new CTFailures(this.repositories);
        this._updater = new CTScheduledUpdater(this.update.bind(this), kUpdateFrequency);
        this._analytics = new Analytics('UA-55762617-1');
        this._rotations = CTRotations.getInstance();
        this._rotations.update();
      },

      ready: function() {
        this.update();
      },

      update: function() {
        if (this._promise)
          return;
        this.$.spinner.active = true;

        this._promise = Promise.all(
          [this.repositories.update(),
           this.failures.update(),
           this.$.trooperBanner.update()]).then(this._updateCompleted.bind(this));
      },

      failureGroupKeyChanged: function() {
        this.examinedFailureGroup = null;
        this._pendingFailureGroupKey = this.failureGroupKey;
        this._updateCompleted();
      },

      _updateCompleted: function() {
        this._promise = null;
        this.$.spinner.active = false;
        // FIXME: Shouldn't have to do this, but $ doesn't contain dynamically inserted
        // elements (app-router dynamically inserts resultsPanel if some other route was
        // in the initial page load).  This logic should probably be pushed down into
        // ct-results-panel and ct-unexpected-failures.
        var unexpected = this.querySelector('::shadow #unexpected');
        if (unexpected) {
          unexpected.update();
        }
        if (!this.failures.failures)
          return;
        this.alertsHistoryKey = this.failures.alertsHistoryKey;
        if (!this._pendingFailureGroupKey)
          return;
        this.examinedFailureGroup = this.failures.failures[this.tree].find(function(group) {
          return group.key == this._pendingFailureGroupKey;
        }.bind(this));
        var res = this.querySelector('::shadow #resultsPanel');
        if (!res) {
          return;
        }
        res.group = this.examinedFailureGroup;
        if (!this.examinedFailureGroup) {
          this.asyncFire('navigate', {
            url: this.tree,
            replaceState: true
          });
        }

        this._pendingFailureGroupKey = '';
      },
      fileSoMBug: function() {
        var url = 'https://code.google.com/p/chromium/issues/entry' +
            '?template=Build%20Infrastructure&labels=Infra-Monitoring,SheriffOMatic,Pri-2&' +
            'cc=seanmccullough@chromium.org&'+
            `comment=Problem+with+Sheriff-o-Matic:%0A${encodeURI(window.location.href)}%0A`;
        if (this.alertsHistoryKey) {
          url += `%0AAlerts+history+key:%0A${this.alertsHistoryKey}%0A`;
        }
        window.open(url, '_blank');
      },
    });
  </script>
</polymer-element>
